module.exports = (app) => {
  const express = require('express')
  const authMiddleware = require('../../middleware/Auth')
  const AdminUser = require('../../models/AdminUser')
  const assert = require('http-assert')
  const jwt = require('jsonwebtoken')
  require('require-all')(__dirname + '/../../models')
  // 设置子路由
  const router = express.Router({
    mergeParams: true
  })
  const inflection = require('inflection')

  router.post('/', async (req, res) => {
    const model = await req.Model.create(req.body)
    res.send(model)
  })

  // 判断是否有请求头中间件

  router.get('/', async (req, res) => {
    const queryOptions = {}
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent'
    } else if (req.Model.modelName === 'Article') {
      queryOptions.populate = 'categories'
    }
    const items = await req.Model.find().setOptions(queryOptions)
    res.send(items)
  })
  router.get('/:id', async (req, res) => {
    const model = await req.Model.findById(req.params.id)
    res.send(model)
  })
  router.put('/:id', async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send(model)
  })
  router.delete('/:id', async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id)
    res.send({
      message: 'success'
    })
  })

  app.use(
    '/admin/api/rest/:resource',
    authMiddleware(),
    async (req, res, next) => {
      const modelName = inflection.classify(req.params.resource)
      req.Model = require(`../../models/${modelName}`)
      next()
    },
    router
  )

  const multer = require('multer')
  const upload = multer({ dest: __dirname + '/../../uploads' })
  app.post(
    '/admin/api/upload',
    authMiddleware(),
    upload.single('file'),
    async (req, res) => {
      const file = req.file
      // 文件地址位置
      file.url = `http://localhost:3000/uploads/${file.filename}`
      res.send(file)
    }
  )

  app.post('/admin/api/login', async (req, res) => {
    // 1. 根据用户名查找用户
    const { username, password } = req.body
    const user = await AdminUser.findOne({ username }).select('+password')
    assert(user, 422, '用户不存在')
    // 2. 校验密码
    const isValid = require('bcrypt').compareSync(password, user.password)
    assert(isValid, 422, '密码错误')
    // 3. 返回token
    const token = jwt.sign({ id: user._id }, app.get('secret'))
    res.send(token)
  })

  app.use(async (err, req, res, next) => {
    return res.status(err.statusCode || 500).send({
      message: err.message
    })
  })
}
